require('page/common/header/index.js');
var _util = require('../../util/util.js');
require('./index.css');

var _account_service = require('service/account-service.js');
var mCode = "#";

var userLogin = {
    init : function(){
        $('#loginMsg').hide();
        this.bindEvents();
        return this;
    },
    bindEvents : function(){
        var _this = this;
        $('#submit').click(
            function(){
                _this.submit();
            }
        );
        $('#needCode').click(
            function(){
                _this.sendCode();
            }
        )
    },
    sendCode : function(){
        _account_service.sendCode(
            {
                "memPhone" : $.trim($('#memPhone').val()),
            },
            function(res){
                console.log(res);
                mCode = res;
                console.log(mCode);
            },
            function(errMsg){
                $('#loginMsg').show().text(errMsg);
            }
        );
    },
    submit : function(){
        var formData = {
            username : $.trim($('#username').val()),
            password : $.trim($('#password').val())
        };
        var validationResult = this.formValidation(formData);
        if(validationResult.status){
            //向服务器发送登录请求
            _account_service.login(
                formData,
                function(res){
                    window.location.href=_util.getURLParam('redirect')||'./catalog-main.html';
                },
                function(errMsg){
                    $('#loginMsg').show().text(errMsg);
                }
                );
        }else{
            $('#loginMsg').show().text(validationResult.msg);
        }
    },
    formValidation : function(formData){
        var result = {
            status : false,
            msg    : ''
        };
        if(!_util.validateField('require',formData.username)){
            result.msg = '用户名不能为空';
            return result;
        }
        if(!_util.validateField('require',formData.password)){
            result.msg = '密码不能为空';
            return result;
        }
        // if(!_util.validateField('require',$.trim($('#mCode').val()))){
        //     result.msg = '验证码不能为空';
        //     return result;
        // }
        // if(!($.trim($('#mCode').val()) == mCode)){
        //     result.msg = '验证码错误';
        //     return result;
        // }
        //校验通过
        result.status = true;
        result.msg = '校验通过';
        return result;
    }
};

module.exports = userLogin.init();
